import {
  SET_IS_BLOG_RENDER_COMPLETE,
  SET_BLOG_PASSWORD_DIALOG_VISIBLE,
  SET_BLOG_PASSWORD_FORM,
  SET_IS_BLOG_TO_HOME,
} from "@/store/mutations-types"
import router from "@/router"
import Vue from 'vue'
import { validateBlogPasswordCorrect } from "@/api/blog"
const blog = {
  state: {
    //博客文章渲染完成的标记
    isBlogRenderComplete: false,
    //受保护文章密码对话框
    blogPasswordDialogVisible: false,
    blogPasswordForm: {
      blogId: 0,
      password: ''
    },
    //文章页面路由到首页的标记
    isBlogToHome: false,
  },

  mutations: {
    [SET_IS_BLOG_RENDER_COMPLETE] (state, ok) {
      state.isBlogRenderComplete = ok
    },
    [SET_BLOG_PASSWORD_DIALOG_VISIBLE] (state, visible) {
      state.blogPasswordDialogVisible = visible
    },
    [SET_BLOG_PASSWORD_FORM] (state, form) {
      state.blogPasswordForm = form
    },
    [SET_IS_BLOG_TO_HOME] (state, isBlogToHome) {
      state.isBlogToHome = isBlogToHome
    },
  },

  actions: {
    /**
     * 跳转到博客文章界面
     * 
     * @param {*} param0 
     * @param {*} blog 
     * @returns 
     */
    goBlogPage ({ commit }, blog) {
      if (blog.showPermission === 3) {
        const blogToken = Vue.ls.get(`blog${blog.id}`)
        //对于密码保护文章，博主身份Token和经过密码验证后的Token都可以跳转路由，再由后端验证Token有效性
        if (blogToken) {
          // TODO 校验token的正确性
          validateBlogPasswordCorrect({
            id: blog.id,
            token: blogToken
          }).then(res => {
            if (res.data) {
              return router.push(`/blog/${blog.id}`)
            } else {
              Vue.ls.remove(`blog${blog.id}`)
              commit(SET_BLOG_PASSWORD_FORM, { blogId: blog.id, password: '' })
              commit(SET_BLOG_PASSWORD_DIALOG_VISIBLE, true)
            }
          })
        } else {
          commit(SET_BLOG_PASSWORD_FORM, { blogId: blog.id, password: '' })
          commit(SET_BLOG_PASSWORD_DIALOG_VISIBLE, true)
        }

      } else {
        Vue.ls.remove(`blog${blog.id}`)
        router.push(`/blog/${blog.id}`)
      }
    },
  }
}

export default blog